const cloud = require('wx-server-sdk');

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        // 请求参数
        let {
            pageNum = 1, pageSize = 10, conditions,
        } = event.data

        // 查询数据
        const data = await db.collection('agentConsumeRecord').where(conditions).get()
        console.log("data-----",data)
        // 嵌套数据分页
        let dataList = []
        data.data[0].consumeRecord.forEach(item => {
            const nestedStart = (pageNum - 1) * pageSize
            const nestedEnd = nestedStart + pageSize
            dataList = data.data[0].consumeRecord.slice(nestedStart, nestedEnd)

            // 日期格式化
            const date = new Date(item.consumeTime)
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            // 时、分、秒
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            item.consumeTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        })
        // 返回查询结果
        return {
            code: 200,
            msg: "操作成功",
            data: dataList,
            total: data.data[0].consumeRecord.length,
            totalPages: Math.ceil(data.data[0].consumeRecord.length / pageSize),
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
};